<template>
    <div class="register-container">
        <div class="register-background">
            <div class="background-shapes">
                <div class="shape shape-1"></div>
                <div class="shape shape-2"></div>
                <div class="shape shape-3"></div>
            </div>
        </div>
        
        <div class="register-card">
            <div class="card-header">
                <div class="logo-section">
                    <div class="logo-icon">
                        <el-icon><UserFilled /></el-icon>
                    </div>
                    <h1 class="register-title">创建账户</h1>
                    <p class="register-subtitle">加入 Haoke 平台大家庭</p>
                </div>
            </div>
            
            <div class="card-body">
                <el-form 
                    :model="form" 
                    :rules="rules" 
                    ref="ruleFormRef"
                    class="register-form"
                    @submit.prevent="submitForm(ruleFormRef)"
                >
                    <el-form-item prop="username">
                        <el-input
                            v-model="form.username"
                            placeholder="请输入用户名"
                            class="form-input"
                            size="large"
                            :prefix-icon="User"
                        />
                    </el-form-item>
                    
                    <el-form-item prop="email">
                        <el-input
                            v-model="form.email"
                            placeholder="请输入邮箱地址"
                            class="form-input"
                            size="large"
                            :prefix-icon="Message"
                        />
                    </el-form-item>
                    
                    <el-form-item prop="password">
                        <el-input
                            v-model="form.password"
                            type="password"
                            placeholder="请输入密码"
                            class="form-input"
                            size="large"
                            :prefix-icon="Lock"
                            show-password
                        />
                    </el-form-item>
                    
                    <el-form-item prop="confirmPassword">
                        <el-input
                            v-model="form.confirmPassword"
                            type="password"
                            placeholder="请确认密码"
                            class="form-input"
                            size="large"
                            :prefix-icon="Lock"
                            show-password
                        />
                    </el-form-item>
                    
                    <el-form-item prop="verify">
                        <div class="verify-container">
                            <el-input
                                v-model="form.verify"
                                placeholder="请输入验证码"
                                class="form-input verify-input"
                                size="large"
                                :prefix-icon="Key"
                            />
                            <div class="verify-image-container">
                                <img 
                                    class="verify-image" 
                                    alt="验证码" 
                                    :src="verify_src" 
                                    @click="refreshVerification"
                                    title="点击刷新验证码"
                                />
                            </div>
                        </div>
                    </el-form-item>
                    
                    <el-form-item prop="agreement">
                        <el-checkbox v-model="form.agreement" size="large">
                            我已阅读并同意 
                            <el-button type="primary" text>《用户协议》</el-button>
                            和 
                            <el-button type="primary" text>《隐私政策》</el-button>
                        </el-checkbox>
                    </el-form-item>
                    
                    <el-form-item>
                        <el-button 
                            type="primary" 
                            class="register-button"
                            size="large"
                            :loading="loading"
                            @click="submitForm(ruleFormRef)"
                        >
                            <span v-if="!loading">立即注册</span>
                            <span v-else>注册中...</span>
                        </el-button>
                    </el-form-item>
                </el-form>
                
                <div class="card-footer">
                    <div class="login-link">
                        <span>已有账号？</span>
                        <el-button 
                            type="primary" 
                            text 
                            @click="router.push('/user/login')"
                        >
                            立即登录
                        </el-button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { reactive, ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
    User, 
    UserFilled,
    Lock, 
    Key, 
    Message
} from '@element-plus/icons-vue'

import { register } from '@/api/user'

const router = useRouter()
const ruleFormRef = ref()
const loading = ref(false)

// 生成UUID
const generateUUID = () => {
    let d = new Date().getTime()
    let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        let r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16)
    })
    return uuid;
}

const uuid = generateUUID()
const verify_src = ref(`/api/user/verification/register/${uuid}/`)

let verification_timer = null

// 刷新验证码
const refreshVerification = () => {
    verify_src.value = `/api/user/verification/register/${uuid}/?data=${new Date().getTime()}`
    clearTimeout(verification_timer)
    verification_timer = setTimeout(refreshVerification, 1000 * 60 * 3)
}

// 表单数据
const form = reactive({
    username: '',
    email: '',
    password: '',
    confirmPassword: '',
    uuid: uuid,
    verify: '',
    agreement: false
})

// 验证规则
const rules = reactive({
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
    ],
    email: [
        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能低于六位', trigger: 'blur' }
    ],
    confirmPassword: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        { 
            validator: (rule, value, callback) => {
                if (value !== form.password) {
                    callback(new Error('两次输入的密码不一致'))
                } else {
                    callback()
                }
            }, 
            trigger: 'blur' 
        }
    ],
    verify: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
        { min: 4, max: 4, message: '验证码长度为四位', trigger: 'blur' }
    ],
    agreement: [
        { 
            validator: (rule, value, callback) => {
                if (!value) {
                    callback(new Error('请同意用户协议和隐私政策'))
                } else {
                    callback()
                }
            }, 
            trigger: 'change' 
        }
    ]
})

// 提交表单
const submitForm = async (formEl) => {
    if (!formEl) return
    
    loading.value = true
    
    try {
        await formEl.validate()
        
        await register(form)
        
        ElMessage({
            message: '注册成功！请使用新账号登录',
            type: 'success',
            duration: 2000
        })
        
        // 延迟跳转到登录页面
        setTimeout(() => {
            router.push({ name: 'Login' })
        }, 1500)
        
    } catch (error) {
        console.error('注册失败:', error)
        
        if (error.response?.data) {
            const errorData = error.response.data
            for (let key in errorData) {
                ElMessage({
                    message: errorData[key][0] || '注册失败',
                    type: 'error',
                    duration: 3000
                })
            }
        } else {
            ElMessage({
                message: '注册失败，请检查网络连接',
                type: 'error',
                duration: 3000
            })
        }
        
        refreshVerification()
    } finally {
        loading.value = false
    }
}

onMounted(() => {
    refreshVerification()
})

onUnmounted(() => {
    if (verification_timer) {
        clearTimeout(verification_timer)
    }
})
</script>

<style lang="less" scoped>
.register-container {
    min-height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    overflow: hidden;
}

.register-background {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
    z-index: 0;
}

.background-shapes {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    overflow: hidden;
    
    .shape {
        position: absolute;
        border-radius: 50%;
        background: rgba(255, 255, 255, 0.1);
        animation: float 6s ease-in-out infinite;
        
        &.shape-1 {
            width: 200px;
            height: 200px;
            top: -100px;
            left: -100px;
            animation-delay: 0s;
        }
        
        &.shape-2 {
            width: 150px;
            height: 150px;
            top: 50%;
            right: -75px;
            animation-delay: 2s;
        }
        
        &.shape-3 {
            width: 100px;
            height: 100px;
            bottom: -50px;
            left: 30%;
            animation-delay: 4s;
        }
    }
}

.register-card {
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(20px);
    border-radius: 20px;
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
    padding: 40px;
    width: 100%;
    max-width: 480px;
    position: relative;
    z-index: 1;
    border: 1px solid rgba(255, 255, 255, 0.2);
    max-height: 90vh;
    overflow-y: auto;
}

.card-header {
    text-align: center;
    margin-bottom: 30px;
    
    .logo-section {
        .logo-icon {
            width: 80px;
            height: 80px;
            margin: 0 auto 20px;
            background: linear-gradient(45deg, #11998e, #38ef7d);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 8px 24px rgba(17, 153, 142, 0.3);
            
            .el-icon {
                font-size: 36px;
                color: white;
            }
        }
        
        .register-title {
            font-size: 32px;
            font-weight: 700;
            color: #2c3e50;
            margin-bottom: 8px;
            letter-spacing: 1px;
        }
        
        .register-subtitle {
            color: #7f8c8d;
            font-size: 16px;
            margin: 0;
        }
    }
}

.register-form {
    .form-input {
        margin-bottom: 4px;
        
        :deep(.el-input__wrapper) {
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            border: 1px solid rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
            
            &:hover {
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            }
            
            &.is-focus {
                box-shadow: 0 4px 12px rgba(17, 153, 142, 0.3);
                border-color: #11998e;
            }
        }
    }
    
    .verify-container {
        display: flex;
        gap: 12px;
        align-items: center;
        
        .verify-input {
            flex: 1;
        }
        
        .verify-image-container {
            .verify-image {
                width: 120px;
                height: 40px;
                border-radius: 8px;
                cursor: pointer;
                border: 1px solid rgba(0, 0, 0, 0.1);
                transition: all 0.3s ease;
                
                &:hover {
                    transform: scale(1.05);
                    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
                }
            }
        }
    }
    
    .register-button {
        width: 100%;
        height: 50px;
        border-radius: 12px;
        font-size: 16px;
        font-weight: 600;
        background: linear-gradient(45deg, #11998e, #38ef7d);
        border: none;
        box-shadow: 0 6px 20px rgba(17, 153, 142, 0.3);
        transition: all 0.3s ease;
        
        &:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(17, 153, 142, 0.4);
        }
        
        &:active {
            transform: translateY(0);
        }
    }
}

.card-footer {
    text-align: center;
    
    .login-link {
        margin-top: 20px;
        color: #7f8c8d;
        
        span {
            margin-right: 8px;
        }
    }
}

/* 动画效果 */
@keyframes float {
    0%, 100% {
        transform: translateY(0px);
    }
    50% {
        transform: translateY(-20px);
    }
}

/* 响应式设计 */
@media (max-width: 768px) {
    .register-card {
        margin: 20px;
        padding: 30px 20px;
        max-width: none;
    }
    
    .card-header {
        .logo-section {
            .register-title {
                font-size: 28px;
            }
        }
    }
    
    .verify-container {
        flex-direction: column;
        gap: 8px;
        
        .verify-input {
            width: 100%;
        }
        
        .verify-image-container {
            align-self: center;
        }
    }
}
</style> 